package com.example.reagent_management.ui.operatedialog.viewmodle

import androidx.lifecycle.*
import androidx.paging.PagingData
import androidx.paging.cachedIn
import androidx.paging.filter
import androidx.paging.map
import com.example.reagent_management.room.entity.GetAllCounts
import com.example.reagent_management.room.entity.InStoreChoose
import com.example.reagent_management.room.entity.ReagentOperate
import com.example.reagent_management.ui.operatedialog.repository.StoreRepository
import com.kunminx.architecture.ui.callback.UnPeekLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class StoreViewModel @Inject constructor(
    private val storeRepository: StoreRepository
) : ViewModel() {
    suspend fun insertOperate(reagentOperate: ReagentOperate): Long {
        return storeRepository.insertOperate(reagentOperate)
    }

    //库存总数量  批号+试剂id
    suspend fun getLastCounts(batch: String, reagent_id: Long): GetAllCounts? {
        return storeRepository.getLastCounts(batch, reagent_id)
    }

    //查询批号
    val batches = UnPeekLiveData<PagingData<InStoreChoose>>()
    fun batchList(reagentId: Long, filter: String): Job {
        return viewModelScope.launch {
            storeRepository.getBatchList(reagentId)
                .mapLatest { its ->
                    delay(50)
                    its.filter {
                        //过滤掉已出库完的,过期的无所谓
                        if (filter.isNotEmpty()) {
                            it.inCounts != 0L && (it.inCounts.toString().contains(filter)
                                    || it.batch.contains(filter) || it.supplier.contains(filter)
                                    )
                        } else {
                            it.inCounts != 0L
                        }
                    }
                }
                .flowOn(Dispatchers.Default)
                .cachedIn(viewModelScope)
                .collect {
                    batches.postValue(it)
                }
        }
    }

    /*
    *更新num字段
    * */
    fun updateInStore(num: Long, storeId: Long): Int {
        return storeRepository.updateInStore(num, storeId)
    }

    /*
    * 更新总数
    * */
    fun updateLastCounts(counts: Long, storeId: Long): Int {
        return storeRepository.updateLastCounts(storeId, counts)
    }

    val insertSuccess: MutableLiveData<Boolean> = MutableLiveData<Boolean>(false)

    companion object {
        const val TAG = "InStoreViewModel"
    }
}

